<template>
  <div class="chart-container" :style="{ width, height }" ref="chartRef"></div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import echarts from "echarts/core";
import { BarChart } from "echarts/charts";
import { TitleComponent, LegendComponent, TooltipComponent, AxisComponent, ToolboxComponent } from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

// 注册所需组件
echarts.use([TitleComponent, LegendComponent, TooltipComponent, AxisComponent, ToolboxComponent, BarChart, CanvasRenderer]);

const props = defineProps({
  width: { type: String, default: "1400px" },
  height: { type: String, default: "800px" },
  chartData: {
    type: Object,
    default: () => ({
      xAxisData: ["2024年5月1日", "2024年5月2日", "2024年5月3日", "2024年5月4日", "2024年5月5日"],
      seriesData: [
        { name: "上海南", data: [null, 0, null, null, null] },
        { name: "上海虹桥", data: Array(5).fill(null) },
        { name: "乌鲁木齐", data: Array(5).fill(null) },
        { name: "重庆北", data: Array(5).fill(null) },
        { name: "重庆西", data: Array(5).fill(null) }
      ]
    })
  }
});

const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value, "light", { renderer: "canvas" });
  updateChart();
};

// 更新图表配置
const updateChart = () => {
  const option = {
    animation: true,
    series: props.chartData.seriesData.map(series => ({
      ...series,
      type: "bar",
      stack: "stack1",
      barCategoryGap: "20%",
      barGap: "30%",
      label: { show: false }
    })),
    legend: [
      {
        data: props.chartData.seriesData.map(series => series.name),
        type: "scroll",
        left: "center",
        bottom: "1%",
        orient: "horizontal"
      }
    ],
    tooltip: {
      show: true,
      trigger: "item",
      axisPointer: { type: "line" }
    },
    xAxis: [
      {
        name: "日期",
        data: props.chartData.xAxisData,
        axisLabel: { rotate: 45 }
      }
    ],
    yAxis: [{ name: "车次数量" }],
    title: [
      {
        text: "各出发站每日车次数量统计",
        subtext: "数据范围: 2024年5月1日 至 2024年5月5日",
        left: "center"
      }
    ],
    toolbox: {
      orient: "horizontal",
      left: "80%",
      feature: {
        saveAsImage: {},
        restore: {},
        dataView: {},
        dataZoom: {},
        magicType: { type: ["line", "bar", "stack", "tiled"] }
      }
    }
  };

  chartInstance.setOption(option);
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", () => chartInstance?.resize());
});

watch(
  () => props.chartData,
  () => {
    chartInstance?.dispose();
    initChart();
  },
  { deep: true }
);

onUnmounted(() => {
  chartInstance?.dispose();
  window.removeEventListener("resize", () => chartInstance?.resize());
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  min-width: 600px;
  height: 100%;
  min-height: 400px;
}
</style>
